package com.xunfei.noteapp

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.android.material.appbar.MaterialToolbar

class NoteActivity : AppCompatActivity() {
    private lateinit var notetitle: EditText
    private lateinit var notecontent: EditText
    private lateinit var materialToolbar: MaterialToolbar

    private lateinit var action: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_note)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        notetitle = findViewById(R.id.addtitle)
        notecontent = findViewById(R.id.addcontent)
        materialToolbar = findViewById(R.id.materialToolbar)
        setSupportActionBar(materialToolbar)

        val bundle: Bundle? = intent.extras
        action = bundle?.getString("action").toString()
        if(action == "fix")
        {
            var title:String? = bundle?.getString("title")
            var content:String? = bundle?.getString("content")
            notetitle.setText(title)
            notecontent.setText(content)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.note_menu,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.ic_ok -> {
                val intent = Intent()
                intent.putExtra("action",action)
                intent.putExtra("title",notetitle.text.toString())
                intent.putExtra("content",notecontent.text.toString())
                intent.putExtra("timestamp",System.currentTimeMillis())
                setResult(RESULT_OK,intent)
                finish()
            }

            R.id.ic_cancel -> {
                finish()
            }
        }
        return super.onOptionsItemSelected(item)
    }
}